<!-- eslint-disable vue/multi-word-component-names -->
<!-- @Author ： NWJ
        Version ： 1.0 -->

<template>
  <div class="admin-notification-management">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd" style="margin-bottom: 20px;">
        <el-icon><Plus /></el-icon> 添加通知
      </el-button>
      <el-input v-model="searchQuery" placeholder="搜索通知标题" style="width: 200px; margin-left: 20px;" clearable
        @input="handleSearch" />
    </div>

    <!-- 通知列表 -->
    <el-table :data="filteredNotifications" style="width: 100%;height: 90vh;" stripe :header-cell-style="{ color: '#333' }">
      <el-table-column prop="id" label="ID" sortable width="80" />
      <el-table-column prop="title" label="标题" sortable />
      <el-table-column prop="content" label="内容" sortable />
      <el-table-column prop="createdAt" label="创建时间" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total > 0"
      style="margin-top: 20px; text-align: right;"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="total"
      layout="prev, pager, next, jumper"
      @current-change="handlePageChange"
    />

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-icon size="30px"><Loading /></el-icon> 加载中...
    </div>
    <div v-if="error" class="error-state">
      <el-icon size="20px"><Warning /></el-icon> {{ error }}
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAction">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { Loading, Warning, Plus } from '@element-plus/icons-vue'
import { showMsg } from '@/utils/showMsg'
import { layout } from '@/utils/layout'

export default {
  components: {
    Loading,
    Warning,
    Plus
  },
  data()
  {
    return {
      notifications: [], // 所有通知数据
      searchQuery: '', // 搜索关键词
      loading: false, // 加载状态
      error: null, // 错误信息
      dialogVisible: false, // 弹窗状态
      dialogTitle: '', // 弹窗标题
      form: { title: '', content: '' }, // 表单数据
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      formRef: null, // 表单引用
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0 // 总条数
    }
  },
  computed: {
    // 过滤后的通知列表
    filteredNotifications()
    {
      let result = [...this.notifications]
      if (this.searchQuery)
      {
        result = result.filter(item =>
          item.title.toLowerCase().includes(this.searchQuery.toLowerCase())
        )
      }
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.total = result.length
      return result.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
    }
  },
  created()
  {
    this.fetchNotifications()
  },
  methods: {
    // 获取通知列表
    async fetchNotifications()
    {
      this.loading = true
      this.error = null
      try
      {
        const response = await axios.get('/node/articles')
        if (response.data.code === 0)
        {
          this.notifications = response.data.msg || []
          this.total = this.notifications.length
        }
        else
          layout(this, true, '登录凭证失效')
      }
      catch (error)
      {
        layout(this, true, '登录凭证失效')
      }
      finally
      {
        this.loading = false
      }
    },

    // 格式化日期为 YYYY-MM-DD HH:MM:SS
    formatDate(dateStr)
    {
      return new Date(dateStr).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-').replace(/\b(\d)\b/g, '0$1')
    },

    // 处理添加
    handleAdd()
    {
      this.dialogTitle = '添加系统通知'
      this.form = { title: '', content: '' }
      this.dialogVisible = true
    },

    // 处理编辑
    async handleEdit(row)
    {
      this.dialogTitle = '编辑系统通知'
      this.form = { ...row } // 深拷贝原始数据
      this.dialogVisible = true
    },

    // 确认添加/编辑
    confirmAction()
    {
      this.$refs.formRef.validate(async(valid) =>
      {
        if (valid)
        {
          try
          {
            let response
            if (this.dialogTitle === '添加系统通知')
              response = await axios.post('/node/articles', this.form)
            else
            {
              response = await axios.put(`/node/articles/${this.form.id}`, {
                title: this.form.title,
                content: this.form.content
              })
            }
            if (response.data.code === 0)
            {
              showMsg(`${this.dialogTitle === '添加系统通知' ? '添加' : '编辑'}成功`, null, 'success')
              this.fetchNotifications()
              this.dialogVisible = false
            }
            else
              showMsg(`${this.dialogTitle === '添加系统通知' ? '添加' : '编辑'}失败: ${response.data.msg || '未知错误'}`, null, 'warning')
          }
          catch (error)
          {
            layout(this, true, '登录凭证失效')
          }
        }
      })
    },

    // 处理删除
    async handleDelete(id)
    {
      this.$confirm('此操作将永久删除该通知, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() =>
      {
        try
        {
          const response = await axios.delete(`/node/articles/${id}`)
          if (response.data.code === 0)
          {
            showMsg('删除成功', null, 'success')
            this.fetchNotifications()
          }
          else
            layout(this, true, '登录凭证失效')
        }
        catch (error)
        {
          layout(this, true, '登录凭证失效')
        }
      }).catch(() =>
      {
        this.$message.info('已取消删除')
      })
    },

    // 搜索处理
    handleSearch()
    {
      this.currentPage = 1 // 重置到第一页
    },

    // 页码变化
    handlePageChange(page)
    {
      this.currentPage = page
    }
  }
}
</script>

<style scoped>
.admin-notification-management {
  padding: 20px;
  height: 90vh;
  overflow: scroll;
  background-color: #fff;
  color: #333;
}

.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.loading-state,
.error-state {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-state {
  color: #ff4444;
}

:deep(.el-table) {
  background-color: #fff;
  border-radius: 0;
  overflow: hidden;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f5f5 !important;
}

:deep(.el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table__header th) {
  background-color: #f0f0f0; /* 浅灰色表头 */
}

:deep(.el-dialog) {
  border-radius: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
